"""
@author: Sergiy Tsymbalyuk
"""

import logging

from pylons import request, response, session, tmpl_context as c, url
from pylons.i18n import lazy_ugettext as _

from repoze.what.plugins.pylonshq import ActionProtector
from repoze.what.predicates import has_permission

from chowa.lib.site.settings import OptionsFieldSet
from chowa.model.organization import District

from pubservices.lib.base import render, Session, BaseController

log = logging.getLogger(__name__)

class CommonController(BaseController):
    def index(self):
        identity = request.environ.get('repoze.who.identity')
        district = Session.query(District).filter_by(is_primary=True).first()
        district_id = district.id
        if identity:
            user = identity.get('user')
            district_id = user.person.division.district_id
        
        _url = lambda controller, service: url(controller=controller,
                                               action='total',
                                               service=service,
                                               id=district_id)
        c.ut_url = lambda service: _url('utilities', service)
        c.cm_url = lambda service: _url('communications', service)
        return render('/pubservices/index.html')
    
    @ActionProtector(has_permission('pubservices.administer.settings'))
    def settings(self):
        fs = OptionsFieldSet(['pubservices.read_only',
                              'pubservices.current_period'])
        if request.method == 'POST':
            fs.save(request.POST)
        c.form = fs.render()
        return render('/pubservices/settings.html')
